import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View, Button, ScrollView } from "react-native";
import React, { useState, useEffect } from "react";
import ProductList from "./components/ProductList";
import Cart from "./components/Cart";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import HomeScreen from "./components/HomeScreen";

const Stack = createNativeStackNavigator();

export default function App() {
  const [cartItems, setCartItems] = useState([]);

  const handleAddToCart = (product) => {
    const productExists = cartItems.find((item) => item.id === product.id);
    if (productExists) {
      setCartItems(
        cartItems.map((item) =>
          item.id === product.id
            ? { ...productExists, quantity: productExists.quantity + 1 }
            : item
        )
      );
    } else {
      setCartItems([...cartItems, { ...product, quantity: 1 }]);
    }
  };

  const handleRemoveFromCart = (product) => {
    const productExists = cartItems.find((item) => item.id === product.id);
    if (productExists.quantity > 1) {
      setCartItems(
        cartItems.map((item) =>
          item.id === product.id
            ? { ...productExists, quantity: productExists.quantity - 1 }
            : item
        )
      );
    } else {
      setCartItems(cartItems.filter((item) => item.id !== product.id));
    }
  };

  const handleClearCart = () => {
    setCartItems([]);
  };

  return (
    // <NavigationContainer>
    //   <Stack.Navigator initialRouteName="ProductList">
    //     <Stack.Screen
    //       name="HomeScreen"
    //       component={HomeScreen}
    //       options={{ title: "商城主页" }}
    //     />
    //     <Stack.Screen name="ProductList">
    //       {(props) => <ProductList {...props} onAddToCart={handleAddToCart} />}
    //     </Stack.Screen>
    //     <Stack.Screen name="Cart">
    //       {(props) => (
    //         <Cart
    //           {...props}
    //           cartItems={cartItems}
    //           onAdd={handleAddToCart}
    //           onRemove={handleRemoveFromCart}
    //           onClearCart={handleClearCart}
    //         />
    //       )}
    //     </Stack.Screen>
    //   </Stack.Navigator>
    // </NavigationContainer>
    <ScrollView style={styles.scrollView}>
      <View style={styles.container}>
        <ProductList onAddToCart={handleAddToCart} />
        <Cart
          cartItems={cartItems}
          onAdd={handleAddToCart}
          onRemove={handleRemoveFromCart}
          onClearCart={handleClearCart}
        />
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 20,
  },
  scrollView: {
    flex: 1,
  },
});
